﻿using System.Collections.Generic;
using System.Web.Helpers;
using System.Web.Mvc;
using SuCasa.DataAccess;
using SuCasa.Infrastructure;
using SuCasa.Models;
using System.Linq;

namespace SuCasa.Controllers
{
    [Authorize]
    public class CourseController : Controller
    {
        readonly ICourseRepository _courseRepository;
        readonly IMemberRepository _memberRepository;
        readonly ISessionRepository _sessionRepository;

        public CourseController(){
            if (Constants.UseFakes)
            {
                _courseRepository = new FakeCourseRepository();
                _memberRepository = new FakeMemberRepository();
                _sessionRepository = new FakeSessionRepository();
            }
            else{
                _courseRepository = new CourseRepository(SuCasaContext.Instance);
                _memberRepository = new MemberRepository(SuCasaContext.Instance);
                _sessionRepository = new SessionRepository(SuCasaContext.Instance);
            }
        }

        [HttpGet] //course/Add
        public ActionResult Add(){
            var viewModel = new CourseViewModel();
            viewModel.Instructors = _memberRepository.All.Where(x => x.MemberTypeId == 2);
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Add(CourseViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var course = new Course();
                AutoMapper.Mapper.Map(viewModel, course);
                if (!_courseRepository.AddCourse(course))
                {
                    ModelState.AddModelError(string.Empty, "Couldn't persist course.");
                }
            }
            //maybe a success message in the layout
            return RedirectToAction("Index", "Home");
        }


        [HttpGet]
        public ActionResult List()
        {
           
            var viewModel = _courseRepository.GetAll().Select(x => new CourseViewModel
                {
                    CourseId = x.CourseId, 
                    Name = x.Name, 
                    Semester = x.Semester,
                    Location = x.Location,
                    Description = x.Description,
                    ScheduleNotes = x.ScheduleNotes,
                    MinimumAge =  x.MinimumAge,
                    MaximumAge = x.MaximumAge,
                    Capacity = x.Capacity,
                    Students = x.Students,
                    InstructorId = x.InstructorId,
                    Instructors = _memberRepository.All.Where(y => y.MemberTypeId == 2)
                });
            return View(viewModel);
        }

  

        public ActionResult AddStudent(int memberId, int courseId)
        {
           //member repository add course

            var course = _courseRepository.GetCourseBy(x => x.CourseId == courseId);
            _memberRepository.AddCourse(memberId, course);

            return View("AddStudentToCourse", new AddStudentToCourseViewModel { CourseId = courseId });

            //var course = _courseRepository.GetCourseBy(x => x.CourseId == courseId);
            //var member = _memberRepository.GetMemberBy(x => x.MemberId == memberId);

            //_sessionRepository.AddSession(member, course);

            //return View("AddStudentToCourse", new AddStudentToCourseViewModel { CourseId = courseId });

        }

        public ActionResult AddStudentToCourse(int id)
        {
            var course = _courseRepository.GetCourseBy(x => x.CourseId == id);
            var viewModel = new AddStudentToCourseViewModel
            {
                CourseId = course.CourseId,
                CourseName = course.Name
            };
            return View(viewModel);
        }

        public ActionResult StudentSearch(string searchStr, int courseId)
        {
            var members = new List<Member>();
            var course = _courseRepository.GetCourseBy(x => x.CourseId == courseId);
            if (ModelState.IsValid)
            {
                var allmatchingStudents = _memberRepository.GetMembers(searchStr).Where(x => x.MemberTypeId == 1);// && !x.Courses.Where(z => z.CourseId == courseId).Any());
                
                foreach (var matchingStudent in allmatchingStudents){
                    if (!course.Students.Contains(matchingStudent)){
                        members.Add(matchingStudent);
                    }
                }
            }
            var viewModel = new AddStudentToCourseViewModel(searchStr, members)
                {
                    CourseName = course.Name,
                    CourseId = courseId,
                    SearchStr = searchStr
                };
            return View("AddStudentToCourse", viewModel);
        }

        public ActionResult View(int id)
        {
            var currentCourse = _courseRepository.GetCourseBy(x => x.CourseId == id);
            var sessions = new Dictionary<Member, List<Session>>();
            foreach (Member student in currentCourse.Students)
            {
                var studentSessions = _sessionRepository.GetSessionsByCourse(currentCourse).Where(x => x.StudentId == student.MemberId).ToList();
                sessions.Add(student, studentSessions);
            }

            var viewModel = new CourseDisplayViewModel
            {
                Course = currentCourse,
                Sessions = sessions
            };

            return View(viewModel);
        }

        public JsonResult RemoveStudent(int id, int courseId)
        {
            _courseRepository.RemoveStudentFromCourse(courseId, id);
            return Json(new
            {
                id = id,
                message = "success"
            });
        }

        public ActionResult Details(int id)
        {
            
            var course = _courseRepository.GetCourseBy(x => x.CourseId == id);
            var CourseDetailVM = new CourseDetailViewModel();
            CourseDetailVM.CourseId = course.CourseId;
            CourseDetailVM.CourseName = course.Name;
            CourseDetailVM.Instructor = _memberRepository.GetMemberBy(x => x.MemberId == course.InstructorId).Name;
            CourseDetailVM.Students = course.Students;
            return View("Details", CourseDetailVM);
        }


        //course/rollcall
        [HttpGet]
        public ActionResult RoleCall()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RoleCall(RoleCallViewModel model)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }


        public JsonResult UpdateAttendance()
        {
            var result = new { Success = "Success" };
            return Json(result);
        }
        public JsonResult UpdateHomework()
        {
            var result = new { Success = "Success" };
            return Json(result);
        }

    



    }
}
